package com.example.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edu.exceptionhandler.HeartEduException;
import com.example.user.entity.UcenterMember;
import com.example.user.service.UcenterMemberService;
import com.example.user.utils.ConstantWxUtils;
import com.example.user.utils.HttpClientUtils;
import com.example.user.utils.JwtUtils;
import com.google.gson.Gson;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
	
	@Autowired
	UcenterMemberService ucenterMemberService;

    @SuppressWarnings("unchecked")
	@GetMapping("/callback")
    public String callBack(String code,String state){
        System.out.println(code);
        System.out.println(state);
        
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        
        String accessTokenUrl = String.format(baseAccessTokenUrl, 
        		ConstantWxUtils.WX_OPEN_APP_ID,
        		ConstantWxUtils.WX_OPEN_APP_SECRET,
        		code);
        String tokens=null;
        
        try {
			tokens = HttpClientUtils.get(accessTokenUrl);
			System.out.println("accessToken=============" + tokens);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Gson gson = new Gson();
        HashMap<String, String> map= gson.fromJson(tokens, HashMap.class);
        String accessToken = map.get("access_token");
        
        String openid = map.get("openid");
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UcenterMember ucenterMember = ucenterMemberService.getOne(queryWrapper);
        String token=null;
        if(ucenterMember==null) {
        	 String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                     "?access_token=%s" +
                     "&openid=%s";
             String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
             String userInfo=null;
             try {
     			userInfo = HttpClientUtils.get(userInfoUrl);
     			Gson gson2 = new Gson();
     			HashMap<String,String> mapUser  =gson2.fromJson(userInfo, HashMap.class);
     			String nickname = mapUser.get("nickname");
     			String avatar = mapUser.get("headimgurl");
     			System.out.println(avatar);
     			ucenterMember = new UcenterMember();
     			ucenterMember.setAvatar(avatar);
     			ucenterMember.setNickname(nickname);
     			ucenterMember.setOpenid(openid);
     			System.out.println(ucenterMember);
     			
     			ucenterMemberService.save(ucenterMember);
     			System.out.println("hahahahhah");
                System.out.println(ucenterMember.getId());
     			
     			
     			
     			System.out.println(userInfo+"jdklajdlakjf");
     		} catch (Exception e) {
     			// TODO Auto-generated catch block
     			e.printStackTrace();
     		}
        }
        
        token = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
        
       
 
        return "redirect:http://localhost:3000?token="+token;
    }

    @GetMapping("login")
    public String genQrConnect(HttpSession session){

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new HeartEduException(20001, e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
        System.out.println("state = " + state);

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }
}
